// gfreebox - A Freebox remote control
//
// Copyright (C) 2011 Laurent BRULET
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
// 
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "FreeboxInt.h"

#include <curl/curl.h>

static const char *hosts[] = {
    "hd1.freebox.fr",
    "hd2.freebox.fr"
};

FreeboxInt::FreeboxInt(int freeboxNum, const char *code)
{
    SetCode(code);
    if (! ((freeboxNum == 1) || (freeboxNum == 2)))
    {
        m_freeboxNum = freeboxNum - 1;
    }
    else
    {
        m_freeboxNum = 0;
    }
}

FreeboxInt::Error FreeboxInt::SendCommand(const char *key, bool longPress, int repeat)
{
    CURL *curl = 0;
    CURLcode res;

    std::string url("http://");

    char *urlCode = curl_easy_escape(curl, m_code.c_str(), 0);
    char *urlKey  = curl_easy_escape(curl, key, 0);

    url += hosts[m_freeboxNum];
    url += "/pub/remote_control?code=";
    url += urlCode;
    url += "&key=";
    url += urlKey;
    url += "&long=";
    url += longPress ? "1" : "0";
    url += "&repeat=";
    url += repeat ? "1" : "0";

    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        if (res != 0)
        {
            goto error_perform;
        }
    }
    else
    {
        goto error_init;
    }

    curl_free(urlCode);
    curl_free(urlKey);
    return FreeboxInt::ERR_OK;

error_perform:
    curl_free(urlCode);
    curl_free(urlKey);
    return FreeboxInt::ERR_CURLPERFORM;

error_init:
    return FreeboxInt::ERR_CURLINIT;
}

void FreeboxInt::SetCode(const char *code)
{
    printf("FreeboxInt::SetCode: code = %s\n", code);
    m_code = code;
}
